package com.gitee.chessboard.parser;

import com.gitee.chessboard.enums.DictionaryType;
import com.gitee.chessboard.manager.DictionaryManager;
import com.gitee.chessboard.model.dictionary.Dictionary;
import com.gitee.chessboard.model.word.Word;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 支持常量的分析器
 *
 * @author 敲代码的旺财
 * @date 2021/11/24 16:23
 */
public class DefaultConstantDictionaryParser implements ConstantDictionaryParser {

    private DictionaryManager dictionaryManager;

    public DefaultConstantDictionaryParser(DictionaryManager dictionaryManager) {
        this.dictionaryManager = dictionaryManager;
    }

    /**
     * 将常量类解析成字典
     *
     * @param obj 枚举
     * @return 字典
     */
    @Override
    public Dictionary parser(Class<?> obj) {
        List<Word> wordList = new ArrayList<>();
        Field[] constants = obj.getDeclaredFields();
        try {
            for (Field constant : constants) {
                Word newWord = dictionaryManager.getNewWord();
                newWord.setWordCode(constant.getName());
                newWord.setWordName(String.valueOf(constant.get(null)));
                newWord.setDictionaryCode(obj.getSimpleName());
                wordList.add(newWord);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("分析常量失败", e);
        }
        Dictionary dictionary = dictionaryManager.getNewDictionary(wordList);
        dictionary.setDictionaryCode(obj.getSimpleName());
        dictionary.setDictionaryName(obj.getSimpleName());
        dictionary.setDictionaryType(DictionaryType.CONSTANT);
        return dictionary;
    }
}
